package com.shelpe.services.sinbad.controller.sinbad;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.shelpe.services.sinbad.controller.EffectMetricDto;
import com.shelpe.services.sinbad.controller.dto.AdgroupItem;
import com.shelpe.services.sinbad.dto.KeywordDto;
import com.shelpe.services.sinbad.dto.MobileAdgroupDto;
import com.shelpe.services.sinbad.dto.MobileAdgroupsDto;
import com.shelpe.services.sinbad.dto.MobileKeywordsDto;
import com.shelpe.services.sinbad.dto.MobileMessageDto;
import com.shelpe.services.sinbad.dto.AdgroupAndRptAdgroupDto.rptAdgroupVo;
import com.shelpe.services.sinbad.entity.jpa.Adgroup;
import com.shelpe.services.sinbad.entity.jpa.Campaign;
import com.shelpe.services.sinbad.entity.jpa.DriveType;
import com.shelpe.services.sinbad.entity.jpa.MobileAdgroupDetail;
import com.shelpe.services.sinbad.entity.jpa.MobileKeywordsDetail;
import com.shelpe.services.sinbad.entity.jpa.OnlineStatus;
import com.shelpe.services.sinbad.model.Keyword;
import com.shelpe.services.sinbad.model.KeywordExample;
import com.shelpe.services.sinbad.model.RptKeyword;
import com.shelpe.services.sinbad.model.RptKeywordParam;
import com.shelpe.services.sinbad.readdao.KeywordMapper;
import com.shelpe.services.sinbad.repository.jpa.AdgroupRepository;
import com.shelpe.services.sinbad.repository.jpa.CampaignRepository;
import com.shelpe.services.sinbad.repository.jpa.MobileAdgroupRespository;
import com.shelpe.services.sinbad.repository.jpa.MobileKeywordsRepository;
import com.shelpe.services.sinbad.service.KeywordService;
import com.shelpe.services.sinbad.service.RankingService;
import com.shelpe.services.sinbad.service.RptKeywordService;
import com.shelpe.services.sinbad.service.rpt.AdgroupService;
import com.shelpe.services.sinbad.service.simbaproxy.LexiconClient;
import com.shelpe.services.sinbad.service.simbaproxy.LexiconClient.LastSyncDto;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;

@RestController
@RequestMapping(value = "/sinbadservice/v2")
@Api("无线养分相关的API")
public class MobileController {

	@Autowired
	private AdgroupRepository adgroupRepository;
	@Autowired
	private AdgroupService adgroupService;
	@Autowired
	private CampaignRepository campaignRepository;
	@Autowired
	private KeywordMapper keywordMapper;
	@Autowired
	private RptKeywordService rptKeywordService;
	@Autowired
	private RankingService rankingService;
	@Autowired
	private MobileAdgroupRespository mobileAdgroupRespository;
	@Autowired
	private MobileKeywordsRepository mobileKeywordsRepository;
	@Autowired
	private MessageSource messageSource;
	@Autowired
	private LexiconClient lexiconClient;
	@Autowired
	private KeywordService keywordService;

	@ApiOperation(value = "获取可以养分的宝贝")
	@RequestMapping(method = RequestMethod.GET, path = "/users/{user_id}/@mix_adgroups")
	public List<AdgroupItem> findMixAdgroup(@PathVariable("user_id") final long userID) {
		List<AdgroupItem> adgroupItems = new ArrayList<AdgroupItem>();
		List<Long> adgroupIDs = new ArrayList<Long>();
		List<Long> campaignIDs = new ArrayList<Long>();
		List<Adgroup> adgroups = adgroupRepository.findByUserID(userID);
		List<Campaign> campaigns = campaignRepository.findByUserID(userID);
		// 符合养分的计划
		for (Campaign campaign : campaigns) {
			if (campaign.getOnlineStatus() == OnlineStatus.online && campaign.getBudget() >= 100) {
				campaignIDs.add(campaign.getAutoID());
			}
		}
		// 符合养分的宝贝
		Map<Long, Adgroup> adgroupMap = new HashMap<Long, Adgroup>();
		for (Adgroup adgroup : adgroups) {
			if (adgroup.getOnlineStatus() == OnlineStatus.online && campaignIDs.contains(adgroup.getCampaignID())
					&& adgroup.getDriveType().getValue() != 2) {
				adgroupMap.put(adgroup.getAutoID(), adgroup);
				adgroupIDs.add(adgroup.getAutoID());
			}
		}
		Map<Long, Campaign> campaignMap = new HashMap<Long, Campaign>();
		if (campaigns != null && campaigns.size() > 0) {
			for (Campaign campaign : campaigns) {
				campaignMap.put(campaign.getAutoID(), campaign);
			}
		}
		if (adgroupIDs != null && adgroupIDs.size() > 0) {
			List<EffectMetricDto> dtos = adgroupService.adgroupTrendByUserID(userID, adgroupIDs, "mobile", 7);
			for (EffectMetricDto rpt : dtos) {
				if (rpt.getClick() >= 50 && rpt.getRoi() > 0) {
					AdgroupItem adgroupItem = new AdgroupItem();
					adgroupItem.setMobile(new rptAdgroupVo());
					BeanUtils.copyProperties(rpt, adgroupItem);
					BeanUtils.copyProperties(rpt, adgroupItem.getMobile());
					adgroupItem.setCampaignName(campaignMap.get(rpt.getCampaignID()).getTitle());
					adgroupItem.setUserID(campaignMap.get(rpt.getCampaignID()).getUserID());
					adgroupItem.setFirstCreativeTitle(adgroupMap.get(rpt.getAdgroupID()).getProductName());
					adgroupItem.setFirstCreativeImg(adgroupMap.get(rpt.getAdgroupID()).getProductUrl());
					adgroupItems.add(adgroupItem);
				}
				if (rpt.getClick() >= 50 && rpt.getRoi() == 0
						&& (rpt.getFavTotal() + rpt.getCartTotal()) / 7 > (rpt.getClick() / 7) * 0.05) {
					AdgroupItem adgroupItem = new AdgroupItem();
					adgroupItem.setMobile(new rptAdgroupVo());
					BeanUtils.copyProperties(rpt, adgroupItem);
					BeanUtils.copyProperties(rpt, adgroupItem.getMobile());
					adgroupItem.setCampaignName(campaignMap.get(rpt.getCampaignID()).getTitle());
					adgroupItem.setFirstCreativeTitle(adgroupMap.get(rpt.getAdgroupID()).getProductName());
					adgroupItem.setFirstCreativeImg(adgroupMap.get(rpt.getAdgroupID()).getProductUrl());
					adgroupItem.setUserID(campaignMap.get(rpt.getCampaignID()).getUserID());
					adgroupItems.add(adgroupItem);
				}
			}
		}
		List<AdgroupItem> res = new ArrayList<AdgroupItem>();
		for (AdgroupItem adgroupItem : adgroupItems) {
			adgroupItem.setMobileKeywordsNum(adgroupService.sumMobileKeywords(adgroupItem.getAdgroupID()));
			if (adgroupItem.getMobileKeywordsNum() > 0) {
				res.add(adgroupItem);
			}
		}

		return res;
	}

	private List<Long> sumMobileAdgroups(long userID) {
		List<Long> adgroupIDs = new ArrayList<Long>();
		List<Long> campaignIDs = new ArrayList<Long>();
		List<Adgroup> adgroups = adgroupRepository.findByUserID(userID);
		List<Campaign> campaigns = campaignRepository.findByUserID(userID);

		List<Long> response = new ArrayList<Long>();
		// 符合养分的计划
		for (Campaign campaign : campaigns) {
			if (campaign.getOnlineStatus() == OnlineStatus.online && campaign.getBudget() >= 100) {
				campaignIDs.add(campaign.getAutoID());
			}
		}
		// 符合养分的宝贝
		Map<Long, Adgroup> adgroupMap = new HashMap<Long, Adgroup>();
		for (Adgroup adgroup : adgroups) {
			if (adgroup.getOnlineStatus() == OnlineStatus.online && campaignIDs.contains(adgroup.getCampaignID())
					&& adgroup.getDriveType().getValue() != 2) {
				adgroupMap.put(adgroup.getAutoID(), adgroup);
				adgroupIDs.add(adgroup.getAutoID());
			}
		}
		Map<Long, Campaign> campaignMap = new HashMap<Long, Campaign>();
		if (campaigns != null && campaigns.size() > 0) {
			for (Campaign campaign : campaigns) {
				campaignMap.put(campaign.getAutoID(), campaign);
			}
		}
		if (adgroupIDs != null && adgroupIDs.size() > 0) {
			List<EffectMetricDto> dtos = adgroupService.adgroupTrendByUserID(userID, adgroupIDs, "mobile", 7);
			for (EffectMetricDto rpt : dtos) {
				if (rpt.getClick() >= 50 && rpt.getRoi() > 0) {
					response.add(rpt.getAdgroupID());
				}
				if (rpt.getClick() >= 50 && rpt.getRoi() == 0
						&& (rpt.getFavTotal() + rpt.getCartTotal()) / 7 > (rpt.getClick() / 7) * 0.05) {
					response.add(rpt.getAdgroupID());
				}
			}
		}

		List<Long> res = new ArrayList<Long>();
		for (long adgroupID : response) {
			int num = adgroupService.sumMobileKeywords(adgroupID);
			if (num > 0) {
				res.add(adgroupID);
			}
		}
		return res;
	}

	// 获取可养分的关键词个数
	// private int sumMobileKeywords(AdgroupItem adgroup) {
	// List<KeywordDto> dtos = new ArrayList<KeywordDto>();
	// // 获取关键词元数据
	// KeywordExample ex = new KeywordExample();
	// ex.setUserId(adgroup.getUserID());
	// KeywordExample.Criteria criteria = ex.createCriteria();
	// criteria.andAdgroupIdEqualTo(adgroup.getAdgroupID());
	// List<Keyword> keywords = this.keywordMapper.selectByExample(ex);
	//
	// Map<Long, KeywordDto> dtoMap = new HashMap<Long, KeywordDto>();
	// for (Keyword kw : keywords) {
	// KeywordDto dto = new KeywordDto();
	// dto.from(kw, 0);
	// dtoMap.put(kw.getKeywordId(), dto);
	// }
	//
	// RptKeywordParam param = new RptKeywordParam();
	// param.setUserId(adgroup.getUserID());
	// param.setAdgroupId(adgroup.getAdgroupID());
	// param.setupDays(7);
	// param.setupDevice("mobile");
	//
	// List<RptKeyword> rpts = rptKeywordService.getReportsTrend(param);
	// for (RptKeyword rpt : rpts) {
	// if (dtoMap.get(rpt.getKeywordId()).getMobileQscore() > 5
	// && dtoMap.get(rpt.getKeywordId()).getMobileQscore() < 10 &&
	// rpt.getClick() / 7 > 10
	// && rpt.getFavCount() + rpt.getCartTotal() > 0) {
	// KeywordDto dto = dtoMap.get(rpt.getKeywordId());
	// if (dto != null) {
	// dto.from(rpt);
	// }
	// dtos.add(dto);
	// }
	// }
	// this.rankingService.checkKeywordRanking(adgroup.getUserID(), dtos);
	// return dtos.size();
	// }

	@ApiOperation("获取可以养分的关键词")
	@RequestMapping(method = RequestMethod.GET, path = "/adgroups/{adgroup_id}/@mix_keywords")
	public List<KeywordDto> findMixKeyword(@PathVariable("adgroup_id") long adgroupID) {
		List<KeywordDto> dtos = new ArrayList<KeywordDto>();
		Adgroup adgroup = this.adgroupRepository.findOne(adgroupID);
		Assert.notNull(adgroup, "adgroup_not_found");
		// 获取关键词元数据
		KeywordExample ex = new KeywordExample();
		ex.setUserId(adgroup.getUserID());
		KeywordExample.Criteria criteria = ex.createCriteria();
		criteria.andAdgroupIdEqualTo(adgroupID);
		List<Keyword> keywords = this.keywordMapper.selectByExample(ex);

		Map<Long, KeywordDto> dtoMap = new HashMap<Long, KeywordDto>();
		for (Keyword kw : keywords) {
			KeywordDto dto = new KeywordDto();
			dto.from(kw, adgroup.getMobileDiscount());
			dto.from(adgroup);
			dtoMap.put(kw.getKeywordId(), dto);
		}

		// 获取关键词效果数据
		RptKeywordParam param = new RptKeywordParam();
		param.setUserId(adgroup.getUserID());
		param.setAdgroupId(adgroupID);
		param.setupDays(7);
		param.setupDevice("mobile");

		List<RptKeyword> rpts = rptKeywordService.getReportsTrend(param);
		EffectMetricDto adgroupEffectMetirc = adgroupService.report(adgroupID, "mobile", 7, null, null);
		for (RptKeyword rpt : rpts) {
			if (dtoMap.get(rpt.getKeywordId()) != null) {
				if (dtoMap.get(rpt.getKeywordId()).getMobileQscore() > 5
						&& dtoMap.get(rpt.getKeywordId()).getMobileQscore() < 10 && rpt.getClick() >= 10) {
					if (rpt.getRoi() > 0 || (rpt.getRoi() == 0 && (adgroupEffectMetirc.getFavTotal()
							+ adgroupEffectMetirc.getCartTotal()) > adgroupEffectMetirc.getCtr() * 0.05)) {
						KeywordDto dto = dtoMap.get(rpt.getKeywordId());
						if (dto != null) {
							dto.from(rpt);
						}
						dtos.add(dto);
					}
				}
			}
		}
		this.rankingService.checkKeywordRanking(adgroup.getUserID(), dtos);
		if(dtos.size()>0){
			dtos = this.adgroupService.filterMobileKeywordsByMobileRank(dtos, adgroup.getUserID());
		}
		return dtos;
	}

	@ApiOperation("去养分关键词")
	@Transactional
	@RequestMapping(method = RequestMethod.POST, path = "/adgroups/{adgroup_id}/@add_mix_keywords")
	public MobileAdgroupDto addMixKeywords(@PathVariable("adgroup_id") long adgroupID,
			@RequestBody List<Long> keywordIDs) {
		MobileAdgroupDetail mobileAdgroup = new MobileAdgroupDetail();
		Adgroup adgroup = this.adgroupRepository.findOne(adgroupID);
		Assert.notNull(adgroup, "adgroup_not_found");
		mobileAdgroup.from(adgroup);
		mobileAdgroup = this.mobileAdgroupRespository.save(mobileAdgroup);

		// 切成无线养分
		adgroup.setDriveType(DriveType.mix);
		adgroup.setChangeTime(new Date());
		if (adgroup.getLimit() == 0) {
			adgroup.setLimit(350);
		}
		this.adgroupRepository.save(adgroup);

		KeywordExample ex = new KeywordExample();
		ex.setUserId(adgroup.getUserID());
		ex.createCriteria().andKeywordIdIn(keywordIDs);
		List<Keyword> keywords = keywordMapper.selectByExample(ex);
		for (Keyword keyword : keywords) {
			MobileKeywordsDetail mobileKeyword = new MobileKeywordsDetail();
			mobileKeyword.from(keyword, mobileAdgroup.getAutoID());
			this.mobileKeywordsRepository.save(mobileKeyword);
		}

		MobileAdgroupDto dto = new MobileAdgroupDto();
		dto.from(mobileAdgroup);
		return dto;
	}

	@ApiOperation("我的养分宝贝")
	@RequestMapping(method = RequestMethod.GET, path = "/users/{user_id}/@curr_mix_adgroups")
	public MobileAdgroupsDto myMixAdgroups(@PathVariable("user_id") long userID) {
		MobileAdgroupsDto response = new MobileAdgroupsDto();
		List<MobileAdgroupDto> adgroupsDto = new ArrayList<MobileAdgroupDto>();
		List<MobileAdgroupDetail> mobileAdgroups = this.mobileAdgroupRespository.findByUserID(userID);

		List<Long> adgroupIDs = new ArrayList<Long>();
		List<Long> campaignIDs = new ArrayList<Long>();
		Map<Long, Integer> mapKeywordNums = new HashMap<Long, Integer>();

		if (mobileAdgroups != null && mobileAdgroups.size() > 0) {
			// 获取养分宝贝的关键词个数
			List<String> keywordNums = this.mobileKeywordsRepository.findKeywordNumsByMobileAdgroupID();
			for (String num : keywordNums) {
				String[] arrayNums = num.split("-");
				mapKeywordNums.put(Long.parseLong(arrayNums[0]), Integer.parseInt(arrayNums[1]));
			}
			// 养分宝贝基类
			for (MobileAdgroupDetail mobileAdgroup : mobileAdgroups) {
				MobileAdgroupDto dto = new MobileAdgroupDto();
				adgroupIDs.add(mobileAdgroup.getAdgroupID());
				campaignIDs.add(mobileAdgroup.getCampaignID());
				dto.from(mobileAdgroup);
				if(dto.getRemaDays()<0){
					dto.setRemaDays(0);
				}
				adgroupsDto.add(dto);
			}

			List<Adgroup> adgroups = this.adgroupRepository.findByAutoIDIn(adgroupIDs);
			List<Campaign> campaigns = this.campaignRepository.findByAutoIDIn(campaignIDs);
			Map<Long, Campaign> campaignMap = new HashMap<Long, Campaign>();
			if (campaigns != null && campaigns.size() > 0) {
				for (Campaign campaign : campaigns) {
					campaignMap.put(campaign.getAutoID(), campaign);
				}
			}

			Map<Long, Adgroup> adgroupMap = new HashMap<Long, Adgroup>();
			if (adgroups != null && adgroups.size() > 0) {
				for (Adgroup adgroup : adgroups) {
					adgroupMap.put(adgroup.getAutoID(), adgroup);
				}
			}

			for (MobileAdgroupDto adgroupDto : adgroupsDto) {
				adgroupDto.setCampaignName(campaignMap.get(adgroupDto.getCampaignID()).getTitle());
				adgroupDto.setProductTitle(adgroupMap.get(adgroupDto.getAdgroupID()).getProductName());
				adgroupDto.setProductImg(adgroupMap.get(adgroupDto.getAdgroupID()).getProductUrl());
				adgroupDto.setKeywordsNum(mapKeywordNums.get(adgroupDto.getMobileAdgroupID()));
			}
			response.setMixAdgroups(adgroupsDto);
		}
		// 可养分的宝贝ID
		List<Long> ids = this.sumMobileAdgroups(userID);
		response.setRemainderNum(ids.size());
		return response;
	}

	@ApiOperation("根据养分宝贝获取养分关键词")
	@RequestMapping(method = RequestMethod.GET, path = "/mobileAdgroups/{mobile_adgroup_id}/@mix_keywords_effect")
	public List<MobileKeywordsDto> myMixKeyWords(@PathVariable("mobile_adgroup_id") long mobileAdgroupID) {
		List<MobileKeywordsDto> mobileKeywordsRpt = new ArrayList<MobileKeywordsDto>();
		List<MobileKeywordsDetail> mobileKeywords = this.mobileKeywordsRepository
				.findByMobileAdgroupID(mobileAdgroupID);
		MobileAdgroupDetail mobileAdgroup = this.mobileAdgroupRespository.findOne(mobileAdgroupID);

		// 获取关键词效果数据
		RptKeywordParam param = new RptKeywordParam();
		param.setUserId(mobileAdgroup.getUserID());
		param.setAdgroupId(mobileAdgroup.getAdgroupID());
		param.setupDevice("mobile");
		Date startDate = DateUtils.addDays(DateUtils.truncate(new Date(), Calendar.DATE), -7);
		Date endDate = DateUtils.truncate(new Date(), Calendar.DATE);
		param.setStartDate(DateFormatUtils.format(startDate, RptKeywordParam.FORMAT_DAY));
		param.setEndDate(DateFormatUtils.format(endDate, RptKeywordParam.FORMAT_DAY));
		List<RptKeyword> rpts = rptKeywordService.getReportsTrend(param);

		Map<Long, RptKeyword> mapKeywordRpts = new HashMap<Long, RptKeyword>();
		if (rpts != null && rpts.size() > 0) {
			for (RptKeyword rpt : rpts) {
				mapKeywordRpts.put(rpt.getKeywordId(), rpt);
			}
		}

		if (mobileKeywords != null && mobileKeywords.size() > 0) {
			for (MobileKeywordsDetail detail : mobileKeywords) {
				MobileKeywordsDto dto = new MobileKeywordsDto();
				dto.from(detail);
				dto.setImpressions(mapKeywordRpts.get(detail.getKeywordID()).getImpressions());
				dto.setClick(mapKeywordRpts.get(detail.getKeywordID()).getClick());
				mobileKeywordsRpt.add(dto);
			}
		}
		return mobileKeywordsRpt;
	}

	@ApiOperation("删除我的养分宝贝")
	@Transactional
	@RequestMapping(method = RequestMethod.DELETE, path = "/mobileAdgroups/{mobile_adgroup_id}/@delete")
	public Response deleteMobileAdgroup(@PathVariable("mobile_adgroup_id") long mobileAdgroupID) {
		Response response = new Response();
		MobileAdgroupDetail mobileAdgroup = mobileAdgroupRespository.findOne(mobileAdgroupID);
		Assert.notNull(mobileAdgroup, "mobile_adgroup_not_found");
		Adgroup adgroup = adgroupRepository.findOne(mobileAdgroup.getAdgroupID());
		adgroup.setDriveType(mobileAdgroup.getDriveType());
		adgroupRepository.save(adgroup);
		this.mobileKeywordsRepository.deleteByMobileAdgroupID(mobileAdgroupID);
		this.mobileAdgroupRespository.delete(mobileAdgroupID);
		return response;
	}

	@ApiOperation("养分优化记录")
	@RequestMapping(method = RequestMethod.GET, path = "/mobileAdgroups/{mobile_adgroup_id}/@mobileRecords")
	public MobileMessageDto getMobileRecords(@PathVariable("mobile_adgroup_id") long mobileAdgroupID) {
		MobileAdgroupDetail mobileAdgroup = this.mobileAdgroupRespository.findOne(mobileAdgroupID);
		Assert.notNull(mobileAdgroup, "mobile_adgroup_not_found");
		List<MobileKeywordsDetail> mobileKeywords = this.mobileKeywordsRepository
				.findByMobileAdgroupID(mobileAdgroupID);
		Date now = new Date();
		MobileMessageDto message = new MobileMessageDto();
		message.setCreatedTime(mobileAdgroup.getCreatedTime());
		int days = (int) ((now.getTime() - mobileAdgroup.getCreatedTime().getTime()) / 1000 * 60 * 60 * 24);
		if (days > 1) {
			LastSyncDto lastSync = lexiconClient.findLastSyncTime(mobileAdgroup.getUserID(),
					mobileAdgroup.getCampaignID(), mobileAdgroup.getAdgroupID());
			if (lastSync.isRptKeywordsSync()) {
				message.setSyncTime(lastSync.getRptKeywordsSyncTime());
				RptKeywordParam param = RptKeywordParam.init();
				param.setUserId(mobileAdgroup.getUserID());
				param.setAdgroupId(mobileAdgroup.getAdgroupID());
				param.setupDevice("mobile");
				// 昨天关键词移动端效果数据
				List<RptKeyword> lastDayKeywordsRpts = rptKeywordService.getReportsTrend(param);
				// 昨天宝贝移动端效果数据汇总
				RptKeyword lastAdgroupRpt = rptKeywordService.getSummariesMetric(param);

				Date daybefore = DateUtils.addDays(DateUtils.truncate(now, Calendar.DATE), -2);
				param.setStartDate(DateFormatUtils.format(daybefore, RptKeywordParam.FORMAT_DAY));
				param.setEndDate(DateFormatUtils.format(daybefore, RptKeywordParam.FORMAT_DAY));
				// 前天关键词移动端效果数据
				List<RptKeyword> dayBeforeKeywordsRpts = rptKeywordService.getReportsTrend(param);

				// 當前質量得分
				List<Keyword> keywords = keywordService.getKeywords(mobileAdgroup.getUserID(),
						String.valueOf(mobileAdgroup.getAdgroupID()), null);

				Map<Long, RptKeyword> mapLastKeywordsRpts = new HashMap<Long, RptKeyword>();
				Map<Long, RptKeyword> mapDayBeforeKeywordsRpts = new HashMap<Long, RptKeyword>();
				Map<Long, Keyword> mapKeywordsQscores = new HashMap<Long, Keyword>();
				for (RptKeyword rpt : lastDayKeywordsRpts) {
					mapLastKeywordsRpts.put(rpt.getKeywordId(), rpt);
				}
				for (Keyword keyword : keywords) {
					mapKeywordsQscores.put(keyword.getKeywordId(), keyword);
				}
				for (RptKeyword rpt : dayBeforeKeywordsRpts) {
					mapDayBeforeKeywordsRpts.put(rpt.getKeywordId(), rpt);
				}

				List<String> mobileRecords = new ArrayList<String>();
				for (MobileKeywordsDetail mobileKeyword : mobileKeywords) {
					long keywordId = mobileKeyword.getKeywordID();
					RptKeyword lastRptKeyword = mapLastKeywordsRpts.get(keywordId);
					if (mapKeywordsQscores.get(keywordId).getWirelessQscore() > mobileKeyword.getStartQscore()) {
						String[] params = { mobileKeyword.getWord(), mobileKeyword.getStartQscore() + "",
								mapKeywordsQscores.get(keywordId).getWirelessQscore() + "" };
						mobileRecords
								.add(messageSource.getMessage("message.mobile.keyword.qsocre", params, Locale.ENGLISH));
					}
					if (lastRptKeyword.getCtr() > lastAdgroupRpt.getCtr()) {
						float percent = (lastRptKeyword.getCtr() / lastAdgroupRpt.getCtr()) * 100;
						String[] params = { mobileKeyword.getWord(), percent + "" };
						mobileRecords
								.add(messageSource.getMessage("message.mobile.keyword.ctr", params, Locale.ENGLISH));
					}
					if (lastRptKeyword.getRoi() > lastAdgroupRpt.getRoi()) {
						float percent = (lastRptKeyword.getRoi() / lastAdgroupRpt.getRoi()) * 100;
						String[] params = { mobileKeyword.getWord(), percent + "" };
						mobileRecords
								.add(messageSource.getMessage("message.mobile.keyword.roi", params, Locale.ENGLISH));
					}
					// 昨天收藏加购数：
					float lastTotal = lastRptKeyword.getCartTotal() + lastRptKeyword.getFavCount();
					// 前天收藏加购数：
					float daybeforeTotal = mapDayBeforeKeywordsRpts.get(keywordId).getCartTotal()
							+ mapDayBeforeKeywordsRpts.get(keywordId).getFavCount();
					if (lastTotal > daybeforeTotal) {
						float percent = (lastTotal / daybeforeTotal) * 100;
						String[] params = { mobileKeyword.getWord(), percent + "" };
						mobileRecords.add(
								messageSource.getMessage("message.mobile.keyword.favandcart", params, Locale.ENGLISH));
					}
					if (lastRptKeyword.getSale() > 0) {
						String[] params = { mobileKeyword.getWord(), lastRptKeyword.getSale() + "" };
						mobileRecords
								.add(messageSource.getMessage("message.mobile.keyword.sale", params, Locale.ENGLISH));
					}
					float percet = (lastRptKeyword.getPayCount() / lastAdgroupRpt.getPayCount()) * 100;
					String[] params = { mobileKeyword.getWord(), lastRptKeyword.getPayCount() + "", percet + "" };
					mobileRecords
							.add(messageSource.getMessage("message.mobile.keyword.paytotal", params, Locale.ENGLISH));
				}
				message.setMobileRecords(mobileRecords);
			}

			// message.mobile.keyword.qsocre=您所养的关键词[{0}]的质量得分由{1}分涨至{2}分
			// message.mobile.keyword.ctr=您所养的关键词[{0}]昨日点击率高于点击率的{1}%
			// message.mobile.keyword.roi=您所养的关键词[{0}]昨日ROI高于宝贝ROI的{1}%
			// message.mobile.keyword.favandcart=您所养的关键词[{0}]昨日收藏加购数比前天上升{1}%
			// message.mobile.keyword.sale=您所养的关键词[{0}]昨日已达成{1}单成交
			// message.mobile.keyword.paytotal=您所养的关键词[{0}]昨日支付总金额为{1}，占总宝贝支付金额的{2}%
		}

		return message;
	}

	@Data
	private static class Response {
		private boolean status;
	}
}
